<template>
  <div :id="id" class="k-echart"></div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref, getCurrentInstance, nextTick, watch } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import * as echarts from 'echarts'
import { ECharts } from 'echarts/types/dist/echarts'

export default defineComponent({
  name: 'KEcharts',
  props: {
    option: Object
  },
  setup (props) {
    const id = ref(uuidv4())
    const cur = getCurrentInstance()
    let chart: ECharts | undefined

    onMounted(async () => {
      if (cur?.proxy) {
        chart = echarts.init(cur.proxy.$el)
        chart.setOption(props.option as any, true)
        // 解决宽度不会自适应
        await nextTick()
        chart.resize()
      }
    })

    // 监听option变化重绘图表
    watch(() => props.option, async () => {
      if (chart) {
        chart.setOption(props.option as any, true)
        // 解决宽度不会自适应
        await nextTick()
        chart.resize()
      }
    })

    return {
      id,
      resize: () => {
        if (chart) {
          chart.resize()
        }
      }
    }
  }
})
</script>

<style scoped lang="scss">

</style>
